/**
 * Copyright (c) 2009 Teoti Graphix, LLC See:
 *     http://tkarchitecture.teotigraphix.org
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 * 
 * @author Michael Schmalle mschmalle@teotigraphix.com
 */
package org.teotigraphix.dx.patterns.manager.style
{

import flash.display.DisplayObject;

import mx.styles.CSSStyleDeclaration;
import mx.styles.IStyleClient;
import mx.styles.StyleManager;

import org.teotigraphix.dx.core.ToolKitUtil;
import org.teotigraphix.dx.interfaces.IStyleBindingManager;
import org.teotigraphix.dx.patterns.manager.meta.ClassMetaData;
import org.teotigraphix.dx.patterns.manager.meta.StyleBindingInfo;

[Mixin]

//[ExcludeClass]

/**
 * @private
 * 
 * The default <code>IStyleBindingManager</code> implementation for the toolkit.
 * 
 * <p><em>This class is internal to the toolkit.</em></p>
 * 
 * @author Michael Schmalle
 * @copyright Teoti Graphix, LLC
 * @date 07-20-09
 */
public class StyleBindingManagerImpl
	   implements IStyleBindingManager
{
	include '../../../core/Version.as'
	
	//--------------------------------------------------------------------------
	//
	//  Public Static Initialization
	//
	//--------------------------------------------------------------------------
	
	ToolKitUtil.registerSingleton(
		"org.teotigraphix.dx.interfaces::IStyleBindingManager", 
		StyleBindingManagerImpl);
	
	//--------------------------------------------------------------------------
	//
	//  Public Mixin :: Methods - ISystemManager
	//
	//--------------------------------------------------------------------------
	
	/**
	 * @private
	 */
	public static function init(root:DisplayObject):void
	{
	}
	
	//--------------------------------------------------------------------------
	//
	//  Private Class :: Properties
	//
	//--------------------------------------------------------------------------
	
	/**
	 * @private
	 */
	private static var instance:IStyleBindingManager = null;
	
	//--------------------------------------------------------------------------
	//
	//  Constructor
	//
	//--------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 * @private
	 */
	public function StyleBindingManagerImpl()
	{
	}
	
	//--------------------------------------------------------------------------
	//
	//  IToolKitStyleManager API :: Methods
	//
	//--------------------------------------------------------------------------
	
	/**
	 * @copy org.teotigraphix.dx.interfaces.IStyleBindingManager#initialize()
	 */
	public function initialize(
		metaTarget:Object, styleSource:IStyleClient = null):void 
	{
//		trace("ToolKitStyleManagerImpl::initialize()", metaTarget, styleSource);
		
		if(!styleSource)
			styleSource = metaTarget as IStyleClient;

		var metaData:ClassMetaData = ToolKitUtil.resolveClassMetaData(metaTarget);
		for each(var info:StyleBindingInfo in metaData.styleBindings) 
		{
			internalUpdateStyle(info.id, metaTarget, styleSource, info);
		}
	}
	
	/**
	 * @copy org.teotigraphix.dx.interfaces.IStyleBindingManager#updateStyle()
	 */
	public function updateStyle(
		style:String, metaTarget:Object, styleSource:IStyleClient = null):void
	{
		// if the style is null this means the styleName was set to null
		// and we need to refresh all, re-initialize
		if (style == null)
		{
			initialize(metaTarget, styleSource);
			return;
		}
//		trace("    ToolKitStyleManagerImpl::updateStyle()", style);
		
		if(!styleSource)
			styleSource = metaTarget as IStyleClient;
		
		var info:StyleBindingInfo = getInfo(style, metaTarget);
		if (info)
			internalUpdateStyle(style, metaTarget, styleSource, info);
	}
	
	/**
	 * @copy org.teotigraphix.dx.interfaces.IStyleBindingManager#createSelector()
	 */
	public function createSelector(
		selectorName:String, defaultFactory:Function):CSSStyleDeclaration
	{
		/* Flex 4
		var selector:CSSSelector = new CSSSelector(selectorName, null, null);
		var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration(selectorName);
		
		if (!style)
		{
		    style = new CSSStyleDeclaration(selector);
		}
		
		if (style.defaultFactory == null)
			style.defaultFactory = defaultFactory;
		
		StyleManager.setStyleDeclaration(selectorName, style, true);
		
		return style;
		*/
		return null;
	}
	
	//--------------------------------------------------------------------------
	//
	//  Private :: Methods
	//
	//--------------------------------------------------------------------------
	
	/**
	 * @private
	 */
	private function internalUpdateStyle(
		style:String, 
		metaTarget:Object, styleSource:IStyleClient, 
		info:StyleBindingInfo):void
	{
		var id:String = info.id;
		// 1) If the target actually contains this property name
		if (!(id in metaTarget))
			return;
		
//		trace(">>> ToolKitStyleManagerImpl::internalUpdateStyle()", property);
//		trace("\t " +metaTarget);
		// this 'could' return the default value located on the target
		// if the getStyle() call returned undefined
		var value:* = updateStyleBinding(info, metaTarget, styleSource);

		// 2) If we are not setting the same value
		// 3) If we are not setting a null
		if (value != null /*&& metaTarget[property] != value*/) // affected initialize
		{
//			trace("\t@set " + property + "(" + value + ")");
			metaTarget[id] = value;
		}		
	}
	
	/**
	 * @private
	 */
	private function getInfo(
		style:String, metaTarget:Object):StyleBindingInfo
	{
		var metaData:ClassMetaData = ToolKitUtil.resolveClassMetaData(metaTarget);
		for each(var info:StyleBindingInfo in metaData.styleBindings) 
		{
			if (info.id == style)
				return info;
		}
		return null;
	}
	
	/**
	 * @private
	 */
	private function updateStyleBinding(
		info:StyleBindingInfo, target:Object, styleSource:IStyleClient):Object 
	{
		if (styleSource) 
		{
			var value:* = styleSource.getStyle(info.id);
			// this is saving the default value defined on the Skin (property)
			var none:Object = target[info.id];
			
			if (!StyleManager.isValidStyleValue(value))
			{
				return null;
			}
			
			switch(info.type) 
			{
				case "Boolean":
					return resolveBoolean(value, none);
					break;
				case "Number":
				case "int":
				case "uint":
					return resolveNumber(value, none as Number);
					break;
				case "String":
					return resolveString(value, none as String);
					break;
				default:
					var type:Class = ToolKitUtil.getDefinition(info.type) as Class;
					return resolveClass(value, type, none);
					break;
			}
		}
		
		return none;
	}
	
	/**
	 * @private
	 */
	private function resolveBoolean(value:Object, none:Boolean):Boolean
	{
		return value != null ? value : none;
	}
	
	/**
	 * @private
	 */
	private function resolveNumber(value:Object, none:Number):Number 
	{
		return value != null ? value.valueOf() : none;
	}
	
	/**
	 * @private
	 */
	private function resolveString(value:Object, none:String):String 
	{
		return value != null ? value.toString() : none;
	}

	/**
	 * @private
	 */	
	private function resolveClass(
		value:Object, type:Class, none:Object):Object 
	{
		if (value is type) 
		{
			return value;
		} 
		else if (value is Class) 
		{
			var clazz:Class = value as Class;
			
			if (none != null)
			{
				var newName:String = ToolKitUtil.getClassName(clazz);
				var noneName:String = ToolKitUtil.getClassName(none);
				
				// if match, they are the exact same class, don't instantiate
				if (newName == noneName)
					return null;
			}

			var instance:Object = new clazz();

			if (instance is type) 
			{
				return instance;
			}
		}
		return none;
	}
	
	//--------------------------------------------------------------------------
	//
	//  Public Class :: Methods
	//
	//--------------------------------------------------------------------------
	
    /**
     * @private
     */
    public static function getInstance():IStyleBindingManager
    {
        if (!instance) 
			instance = new StyleBindingManagerImpl();
        return instance;
    }
}
}